package com.example.himalaya2.presenters;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;

import com.example.himalaya2.api.XimalayaApi;
import com.example.himalaya2.base.BaseApplication;
import com.example.himalaya2.interfaces.IPlayerCallback;
import com.example.himalaya2.interfaces.IPlayerPresenters;
import com.example.himalaya2.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.track.TrackList;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.constants.PlayerConstants;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class PlayerPresenter implements IPlayerPresenters , IXmAdsStatusListener, IXmPlayerStatusListener {

    private static final String TAG = "PlayerPresenter" ;
    private static PlayerPresenter sInstant = null;
    private XmPlayerManager mPlayerManager;
    private boolean isPlayListSet = false;
    private List<IPlayerCallback> mIPlayerCallbacks = new ArrayList<>();
    private String mTrackTitle;
    private Track mCurrentTrack;
    private int mCurrentIndex = 0;
    private final SharedPreferences mPlayModeSp;
    public static final int PLAY_MODE_LIST_INT = 0;
    public static final int PLAY_MODE_LIST_LOOP_INT = 1;
    public static final int PLAY_MODE_RANDOM_INT = 2;
    public static final int PLAY_MODE_SINGLE_LOOP_INT = 3;
    private XmPlayListControl.PlayMode mCurrentMode = XmPlayListControl.PlayMode.PLAY_MODEL_LIST;

    // sp's key and name
    public static final String PLAY_MODE_SP_NAME = "PlayMode";
    public static final String PLAY_MODE_SP_KEY = "currentPlayMode";
    public static final int DEFAULT_PLAY_INDEX = 0;
    private int mCurrentProgress = 0;
    private int mCurrentDuration = 0;


    private PlayerPresenter(){
        mPlayerManager = XmPlayerManager.getInstance(BaseApplication.getAppContext());
        mPlayerManager.addAdsStatusListener(this); // 注册广告相关的接口
        mPlayerManager.addPlayerStatusListener(this); // 这车播放相关的接口
        // 需要记录当前播放模式
        mPlayModeSp = BaseApplication.getAppContext().getSharedPreferences(PLAY_MODE_SP_NAME, Context.MODE_PRIVATE);

    }

    public static PlayerPresenter getInstance() {
        if (sInstant == null) {
            synchronized (PlayerPresenter.class){
                if (sInstant == null) {
                    sInstant = new PlayerPresenter();
                }
            }
        }
        return sInstant;
    }



    public void setPlayList(List<Track> list,int playIndex) {
        LogUtil.d(TAG,"setPlayList");
        if (mPlayerManager != null) {
            mPlayerManager.setPlayList(list,playIndex);
            isPlayListSet = true;
            mCurrentTrack = list.get(playIndex);
            mCurrentIndex = playIndex;
        }else {
            LogUtil.d(TAG,"mPlayerManager 为空");
        }
    }

    @Override
    public void play() {
        if (isPlayListSet) {
            mPlayerManager.play();
        }
    }

    @Override
    public void pause() {
        if (mPlayerManager !=null) {
            mPlayerManager.pause();
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public void playPre() {
        if (mPlayerManager != null) {
            mPlayerManager.playPre();
        }
    }

    @Override
    public void playNext() {
        if (mPlayerManager != null) {
            mPlayerManager.playNext();
        }
    }

    @Override
    public void switchPlayModel(XmPlayListControl.PlayMode model) {
        // 修改播放模式图标
        if (mPlayerManager != null) {
            mCurrentMode = model;
            mPlayerManager.setPlayMode(model);
        }
        // 通知ui更新街慢
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onPlayModelChange(model);
        }
        // 保存到sp中
        SharedPreferences.Editor edit = mPlayModeSp.edit();
        edit.putInt(PLAY_MODE_SP_KEY,getIntByPlayMode(model));
        edit.commit();
    }

    private int getIntByPlayMode(XmPlayListControl.PlayMode model){
        switch (model) {
            case PLAY_MODEL_SINGLE_LOOP:
                return PLAY_MODE_SINGLE_LOOP_INT;
            case PLAY_MODEL_LIST_LOOP:
                return PLAY_MODE_LIST_LOOP_INT;
            case PLAY_MODEL_RANDOM:
                return PLAY_MODE_RANDOM_INT;
            case PLAY_MODEL_LIST:
                return PLAY_MODE_LIST_INT;
        }
        return PLAY_MODE_LIST_INT;
    }
    private XmPlayListControl.PlayMode getModeByPlayInt(int index){
        switch (index) {
            case PLAY_MODE_SINGLE_LOOP_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;
            case PLAY_MODE_LIST_LOOP_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
            case PLAY_MODE_RANDOM_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
            case PLAY_MODE_LIST_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
        }
        return XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
    }

    @Override
    public void getPlayList() {
        if (mPlayerManager != null) {
            List<Track> tracks = mPlayerManager.getPlayList();
            for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
                iPlayerCallback.onListLoaded(tracks);
            }
        }
    }

    @Override
    public void playByIndex(int index) {
        // 切换播放器 到第index
        if (mPlayerManager != null) {
            mPlayerManager.play(index);
        }

    }

    @Override
    public void seekTo(int index) {
        //  更新播放器的进度
        mPlayerManager.seekTo(index);
    }

    @Override
    public void registerViewCallback(IPlayerCallback iPlayerCallback) {
        // 通知当前的节目
        LogUtil.d(TAG,"registerViewCallback");
        iPlayerCallback.onTrackUpdate(mCurrentTrack,mCurrentIndex);
        // 更新状态
        handlePlayStatus(iPlayerCallback);
        iPlayerCallback.onProgressChange(mCurrentProgress,mCurrentDuration);
        // 从sp中读取播放模式
        int modeIndex = mPlayModeSp.getInt(PLAY_MODE_SP_KEY,PLAY_MODE_LIST_INT);
        mCurrentMode = getModeByPlayInt(modeIndex);
        iPlayerCallback.onPlayModelChange(mCurrentMode);
        if (!mIPlayerCallbacks.contains(iPlayerCallback)) {
            mIPlayerCallbacks.add(iPlayerCallback);
        }
    }

    private void handlePlayStatus(IPlayerCallback iPlayerCallback) {
        int playStatus = mPlayerManager.getPlayerStatus();
        //根据状态调用接口的方法
        if (PlayerConstants.STATE_STARTED == playStatus) {
            iPlayerCallback.onPLayStart();
        } else {
            iPlayerCallback.onPlayPause();
        }
    }


    @Override
    public void unRegisterViewCallback(IPlayerCallback iPlayerCallback) {
        mIPlayerCallbacks.remove(iPlayerCallback);
    }

    //====================广告相关的回调 start ================================
    @Override
    public void onStartGetAdsInfo() {
        LogUtil.d(TAG,"onStartGetAdsInfo");
    }

    @Override
    public void onGetAdsInfo(AdvertisList advertisList) {
        LogUtil.d(TAG,"onGetAdsInfo");
    }

    @Override
    public void onAdsStartBuffering() {
        LogUtil.d(TAG,"onAdsStartBuffering");
    }

    @Override
    public void onAdsStopBuffering() {
        LogUtil.d(TAG,"onAdsStopBuffering");
    }

    @Override
    public void onStartPlayAds(Advertis advertis, int i) {
        LogUtil.d(TAG,"onStartPlayAds");
    }

    @Override
    public void onCompletePlayAds() {
        LogUtil.d(TAG,"onCompletePlayAds");
    }

    @Override
    public void onError(int what, int extra) {
        LogUtil.d(TAG,"onError:  what" + what+"  extra" +extra);
    }

    //====================广告相关的回调 end ================================


    //====================播放器相关的回调 end ================================
    @Override
    public void onPlayStart() {
        LogUtil.d(TAG,"onPlayStart");
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onPLayStart();
        }
    }

    @Override
    public void onPlayPause() {
        LogUtil.d(TAG,"onPlayPause");
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onPlayPause();
        }
    }

    @Override
    public void onPlayStop() {
        LogUtil.d(TAG,"onPlayStop");
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onPlayStop();
        }
    }

    @Override
    public void onSoundPlayComplete() {
        LogUtil.d(TAG,"onSoundPlayComplete");
    }

    @Override
    public void onSoundPrepared() {
        LogUtil.d(TAG,"onSoundPrepared 播放器准备完成1");

        LogUtil.d(TAG,"onSoundPrepared 播放器状态为" + mPlayerManager.getPlayerStatus());
        if (mPlayerManager.getPlayerStatus() == PlayerConstants.STATE_COMPLETED||mPlayerManager.getPlayerStatus() == 2) {  // 列表和位置已经给了播放器 ，放播放器准备完成后，
                                                                                    // 在这个回调里面开启播放

            LogUtil.d(TAG,"onSoundPrepared 播放器准备完成2");

            // 设置播放模式
            mPlayerManager.setPlayMode(mCurrentMode);

            mPlayerManager.play();
        }

    }
    // 判断是否有播放列表
    public boolean hasPlayList() {
        return isPlayListSet;
    }

    @Override
    public void onSoundSwitch(PlayableModel playableModel, PlayableModel playableModel1) { //  playableModel 上一个播放内容，可能为空 ，playableModel1 正在播放内容
        LogUtil.d(TAG,"onSoundSwitch");

        /*if ("track".equals(playableModel1.getKind())) {
            Track currentTrack = (Track) playableModel;
            LogUtil.d(TAG,"title ----  :" +currentTrack.getTrackTitle());
        }
        */
        if (playableModel1 instanceof Track) {
            Track  currentTrack = (Track) playableModel1;
            mCurrentIndex = mPlayerManager.getCurrentIndex();
            LogUtil.d(TAG,"title ----  :" +currentTrack.getTrackTitle());
            mCurrentTrack = currentTrack;
            // 更新标题
            for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
                iPlayerCallback.onTrackUpdate(mCurrentTrack,mCurrentIndex);
            }
        }


    }

    @Override
    public void onBufferingStart() {
        LogUtil.d(TAG,"onBufferingStart");
    }

    @Override
    public void onBufferingStop() {
        LogUtil.d(TAG,"onBufferingStop");
    }

    @Override
    public void onBufferProgress(int i) {
        LogUtil.d(TAG,"onBufferProgress");
    }

    @Override
    public void onPlayProgress(int current, int duration) {
        // LogUtil.d(TAG,"onPlayProgress  current :"+current+"  duration"+duration);
        this.mCurrentProgress = current;
        this.mCurrentDuration = duration;
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onProgressChange(current,duration);
        }
    }

    @Override
    public boolean onError(XmPlayerException e) {
        LogUtil.d(TAG,"onError");
        return false;
    }

    //====================播放器相关的回调 end ================================

    public boolean isPlay(){
        //  返回当前是否正在播放
        return mPlayerManager.isPlaying();
    }

    @Override
    public void reversPlayList() {
        List<Track> tracks = mPlayerManager.getPlayList();
        Collections.reverse(tracks);
        // 第一个参数是播放列表，第二个参数是开始播放的下标
        mCurrentIndex = tracks.size() - 1 - mCurrentIndex;
        mPlayerManager.setPlayList(tracks,mCurrentIndex);
        // 更新ui
        mCurrentTrack = (Track) mPlayerManager.getCurrSound();
        for (IPlayerCallback iPlayerCallback : mIPlayerCallbacks) {
            iPlayerCallback.onListLoaded(tracks);
            iPlayerCallback.onTrackUpdate(mCurrentTrack,mCurrentIndex);
        }
    }

    @Override
    public void playByAlbumId(long id) {
        // 要获取到专辑的内容

        // 开始播放内容
        XimalayaApi.getInstance().getAlbumDetail(new IDataCallBack<TrackList>() {
            @Override
            public void onSuccess(TrackList trackList) {
                // 把专辑的内容 设置给播放器
                List<Track> tracks = trackList.getTracks();
                if (tracks != null || tracks.size()!=0) {
                    mPlayerManager.setPlayList(tracks,DEFAULT_PLAY_INDEX);
                    isPlayListSet = true;
                    mCurrentTrack = tracks.get(DEFAULT_PLAY_INDEX);
                    mCurrentIndex = DEFAULT_PLAY_INDEX;
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(BaseApplication.getAppContext(),"错误码： "+ i + "错误消息 "+s,Toast.LENGTH_SHORT).show();
            }
        },(int)id,1);
    }
}
